package com.ys.web.service.impl;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ys.WebConstants;
import com.ys.extend.utils.TimeUtil;
import com.ys.web.dao.CommonDao;
import com.ys.web.entity.Account;
import com.ys.web.entity.Backup;
import com.ys.web.entity.Company;
import com.ys.web.entity.CustomerFollowUp;
import com.ys.web.entity.Industry;
import com.ys.web.entity.OriginBaidu;
import com.ys.web.entity.User;
import com.ys.web.pojo.AccountInfo;
import com.ys.web.pojo.BaiduPromoteInfo;
import com.ys.web.pojo.CompanyInfo;
import com.ys.web.pojo.VisitAccessKeywordDay;
import com.ys.web.remotemodel.AdOfflineCompanyInfo;
import com.ys.web.remotemodel.RemoteAccountInfo;
import com.ys.web.service.AccountService;
import com.ys.web.service.CompanyService;
import com.ys.web.ws.service.ManageCompanyInfoService;

/**
 * 代运营公司-Service-实现类
 * 
 * @author wdj
 *
 */
@Service("companyService")
@Transactional
public class CompanyServiceImpl implements CompanyService {
	private Logger logger = Logger.getLogger(getClass());

	@Autowired
	private CommonDao commonDao;
	@Autowired
	private AccountService accountService;

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	/** 远程调用-管理KAD系统所需的客户信息 */
	@Resource
	private ManageCompanyInfoService manageCompanyInfoService;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd ");

	@Override
	public void deleteCompany(Integer id) {

		commonDao.executeHql("delete Company where id=" + id);
		List<Account> accounts = commonDao.findByProperty(Account.class, "companyId", id);
		for (Account account : accounts) {
			commonDao.delete(account);
		}

	}

	@Override
	public Integer addCompanyInfo(CompanyInfo companyInfo) {
		Company company = new Company();
		BeanUtils.copyProperties(companyInfo, company);
		company.setRegisterTime(new Date());
		Integer companyId = (Integer) commonDao.save(company);
		List<AccountInfo> accountInfos = companyInfo.getAccoutInfos();
		if (accountInfos != null) {
			for (AccountInfo accountinfo : accountInfos) {
				Account account = new Account();
				BeanUtils.copyProperties(accountinfo, account);
				account.setCompanyId(companyId);
				if ("1".equals(accountinfo.getAccountState())) {
					account.setAccountState((byte) 1);
				} else {
					account.setAccountState((byte) 0);
				}
				// System.out.println("save account");
				commonDao.save(account);
			}
		}
		return companyId;

	}

	/**
	 * 更新或保存客户公司信息
	 */
	@Override
	public Integer saveCompanyInfo(CompanyInfo companyInfo) {
		Integer companyId = null;
		Company company = new Company();
		BeanUtils.copyProperties(companyInfo, company);
		company.setRegisterTime(new Date());
		if (companyInfo.getId() != null) {
			commonDao.saveOrUpdate(company);
			companyId = company.getId();

		} else {
			companyId = (Integer) commonDao.save(company);
		}

		List<AccountInfo> accountInfos = companyInfo.getAccoutInfos();
		List<Integer> saveIds = new ArrayList<Integer>();
		if (accountInfos != null) {
			for (AccountInfo accountinfo : accountInfos) {
				Integer accountId = null;
				// accountinfo id 为0 则默认为新实体用于保存
				// System.out.println("转递id:"+accountinfo.getId());
				if (accountinfo.getId() != null && accountinfo.getId() == 0) {
					accountinfo.setId(null);
				}
				Account account = new Account();
				BeanUtils.copyProperties(accountinfo, account);
				account.setCompanyId(companyId);
				if ("1".equals(accountinfo.getAccountState())) {
					account.setAccountState((byte) 1);
				} else {
					account.setAccountState((byte) 0);
				}

				if (account.getId() == null) {
					// 账户添加的账户不存在返回-1
					if (accountService.isAccountExist(account.getLoginName())) {
						companyId = -1;
						return companyId;
					}

					accountId = (Integer) commonDao.save(account);
				} else {
					commonDao.saveOrUpdate(account);
				}

				accountId = account.getId();
				saveIds.add(accountId);

				// System.out.println(account);
			}
			String deleteIntegers = "";
			for (int i = 1; i <= saveIds.size(); i++) {
				if (i < saveIds.size()) {
					deleteIntegers += saveIds.get(i - 1) + ",";
				} else {
					deleteIntegers += saveIds.get(i - 1);
				}

			}
			if (companyId != null) {
				String findDeleteAccountSql = "";
				if (saveIds.size() > 0) {
					findDeleteAccountSql = "delete from account  where id not in(" + deleteIntegers
							+ ") and company_id=?";
					commonDao.executeSql(findDeleteAccountSql, companyId);
				} else {
					findDeleteAccountSql = "delete from account  where company_id=?";
					commonDao.executeSql(findDeleteAccountSql, companyId);
				}

			}

		}

		return companyId;
	}

	@Override
	public CompanyInfo getCompanyById(Integer id) {
		Company company = commonDao.getEntity(Company.class, id);
		if (company != null) {
			CompanyInfo companyInfo = new CompanyInfo();
			BeanUtils.copyProperties(company, companyInfo);

			String registerTime = sdf.format(company.getRegisterTime());
			companyInfo.setRegisterTime(registerTime);

			Industry industry = commonDao.getEntity(Industry.class, companyInfo.getIndustryId());
			if ("1".equals(company.getCompanyState())) {
				companyInfo.setCompanyStateValue("有效");
			} else if ("0".equals(company.getCompanyState())) {
				companyInfo.setCompanyStateValue("失效");
			}

			if (industry != null) {
				companyInfo.setIndustry(industry.getIndustryName());
			}

			User user = commonDao.getEntity(User.class, company.getUserId());
			companyInfo.setUserId(user.getId());
			companyInfo.setUsername(user.getUsername());

			return companyInfo;

		}
		return null;
	}

	public Boolean isCompanyHasBaidu(Integer companyId) {
		List<OriginBaidu> originBaidus = new ArrayList<OriginBaidu>();
		try {
			DetachedCriteria dc = DetachedCriteria.forClass(OriginBaidu.class);
			Criterion criterion = Restrictions.eq("companyId", companyId);
			dc.add(criterion);
			originBaidus = commonDao.pageList(dc, 0, 1);
			if (originBaidus == null || originBaidus.size() == 0) {
				return false;
			}
			return true;
		} catch (NullPointerException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public List<CompanyInfo> getCompanyBySemUserId(Integer id, int page) throws Exception {
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		DetachedCriteria dc = DetachedCriteria.forClass(Company.class);
		if (id != null) {
			Criterion cr = Restrictions.eq("userId", id);
			dc.add(cr);
		}

		List<Company> companys = commonDao.pageList(dc, WebConstants.MAX_REQUEST_ROW_EACH * (page - 1),
				WebConstants.MAX_REQUEST_ROW_EACH);

		for (Company company : companys) {
			CompanyInfo companyInfo = new CompanyInfo();

			BeanUtils.copyProperties(company, companyInfo);
			companyInfo.setRegisterTime(sdf.format(company.getRegisterTime()));
			if ("1".equals(company.getCompanyState())) {
				companyInfo.setCompanyStateValue("有效");
			} else if ("0".equals(company.getCompanyState())) {
				companyInfo.setCompanyStateValue("失效");
			}

			Industry industry = commonDao.get(Industry.class, company.getIndustryId());
			if (industry != null) {
				companyInfo.setIndustry(industry.getIndustryName());
			}
			User user = commonDao.getEntity(User.class, company.getUserId());
			if (user != null) {
				// 暂时显示管理职员的名字
				companyInfo.setUsername(user.getEmployeeName());
			}

			if (isCompanyHasBaidu(company.getId())) {
				companyInfo.setIsHasBaiduData("1");
			} else {
				companyInfo.setIsHasBaiduData("0");
			}

			List<AccountInfo> accounts = accountService.getAccountByCompanyId(company.getId());
			if (accounts == null || accounts.size() == 0) {
				companyInfo.setIsHasAccount("否");
			} else {
				companyInfo.setIsHasAccount("是");
			}
			companyInfos.add(companyInfo);
		}
		return companyInfos;

	}

	@Override
	public List<CompanyInfo> getAllPageCompany(int page) {

		return null;
	}

	@Override
	public Boolean isCompanyNameExist(String companyname) throws Exception {

		Company company = getCompanyByCompanyName(companyname);

		if (company != null) {

			return true;
		}
		return false;
	}

	@Override
	public Company getCompanyByCompanyName(String companyname) throws Exception {

		Company company = commonDao.findUniqueByProperty(Company.class, "companyName", companyname);
		return company;
	}

	/**
	 * 根据行业查找公司(只显示有百度数据查看的公司)
	 * 
	 * @param industryId
	 *            行业id
	 * @param page
	 *            当前页面
	 * @return 公司列表
	 */
	public List<CompanyInfo> getCompanyByIndustry(Integer industryId, int page) {
		List<CompanyInfo> list = new ArrayList<CompanyInfo>();
		DetachedCriteria dc = DetachedCriteria.forClass(Company.class);
		if (industryId != null) {
			Criterion cr = Restrictions.eq("industryId", industryId);
			dc.add(cr);
		}
		List<Company> companyList = commonDao.pageList(dc, WebConstants.MAX_REQUEST_ROW_EACH * (page - 1),
				WebConstants.MAX_REQUEST_ROW_EACH);
		for (Company company : companyList) {
			CompanyInfo companyInfo = new CompanyInfo();
			try {
				BeanUtils.copyProperties(company, companyInfo);
				companyInfo.setRegisterTime(TimeUtil.getFormatDate(company.getRegisterTime(), "yyyy-MM-dd "));
				if ("1".equals(company.getCompanyState())) {
					companyInfo.setCompanyStateValue("有效");
				} else if ("0".equals(company.getCompanyState())) {
					companyInfo.setCompanyStateValue("失效");
				}
				Industry industry = commonDao.get(Industry.class, company.getIndustryId());
				if (industry != null) {
					companyInfo.setIndustry(industry.getIndustryName());
				}
				User user = commonDao.getEntity(User.class, company.getUserId());
				if (user != null) {
					// 暂时显示管理职员的名字
					companyInfo.setUsername(user.getEmployeeName());
				}

				List<RemoteAccountInfo> accounts = accountService.getAccountByCompanyKADId(company.getId());
				if (accounts == null || accounts.size() == 0) {
					companyInfo.setIsHasAccount("否");
				} else {
					companyInfo.setIsHasAccount("是");
				}

				// 只显示有百度数据查看的公司
				if (isCompanyHasBaidu(company.getId())) {
					companyInfo.setIsHasBaiduData("1");
					list.add(companyInfo);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return list;
	}

	@Override
	public List<CompanyInfo> getCompanyByIndustry(Integer industryId) {
		List<CompanyInfo> list = new ArrayList<CompanyInfo>();
		List<Company> companyList = commonDao.findByProperty(Company.class, "industryId", industryId);
		for (Company company : companyList) {
			CompanyInfo companyInfo = new CompanyInfo();
			try {
				BeanUtils.copyProperties(company, companyInfo);
				companyInfo.setRegisterTime(TimeUtil.getFormatDate(company.getRegisterTime(), "yyyy-MM-dd "));
				if ("1".equals(company.getCompanyState())) {
					companyInfo.setCompanyStateValue("有效");
				} else if ("0".equals(company.getCompanyState())) {
					companyInfo.setCompanyStateValue("失效");
				}
				Industry industry = commonDao.get(Industry.class, company.getIndustryId());
				if (industry != null) {
					companyInfo.setIndustry(industry.getIndustryName());
				}
				User user = commonDao.getEntity(User.class, company.getUserId());
				if (user != null) {
					// 暂时显示管理职员的名字
					companyInfo.setUsername(user.getEmployeeName());
				}
				List<RemoteAccountInfo> accounts = accountService.getAccountByCompanyKADId(company.getId());
				if (accounts == null || accounts.size() == 0) {
					companyInfo.setIsHasAccount("否");
				} else {
					companyInfo.setIsHasAccount("是");
				}

				// 只显示有百度数据查看的公司

				list.add(companyInfo);

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return list;
	}

	@Override
	public List<CompanyInfo> getCompanyNotIsSynchronized() {
		// TODO Auto-generated method stub
		List<Company> companys = commonDao.findByProperty(Company.class, "isSynchronizedToYsb", "0");
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		for (Company company : companys) {
			CompanyInfo companyInfo = new CompanyInfo();
			BeanUtils.copyProperties(company, companyInfo);
			companyInfos.add(companyInfo);
		}

		return companyInfos;
	}

	@Override
	public Company getCompanyEntityById(Integer id) {
		Company company = commonDao.getEntity(Company.class, id);
		return company;
	}

	@Override
	public void saveCompany(Company company) {
		// TODO Auto-generated method stub
		commonDao.saveOrUpdate(company);
	}

	@Override
	public List<CompanyInfo> getAllCompanyInfo() throws Exception {
		// TODO Auto-generated method stub
		List<Company> companys = commonDao.findHql("from Company");
		List<CompanyInfo> companyInfos = new ArrayList<CompanyInfo>();
		for (Company company : companys) {
			CompanyInfo companyInfo = new CompanyInfo();
			BeanUtils.copyProperties(company, companyInfo);

			List<AccountInfo> accountInfos = accountService.getAccountByCompanyId(companyInfo.getId());

			companyInfo.setAccountInfos(accountInfos);

			companyInfo.setAccountInfoArray(accountInfos.toArray(new AccountInfo[accountInfos.size()]));
			companyInfos.add(companyInfo);

		}
		return companyInfos;
	}

	/**
	 * 获取sem要 管理的公司信息-远程调用
	 * 
	 * @param userIdKAD
	 *            sem用户id
	 * @return
	 */
	@Override
	public List<CompanyInfo> getRemoteCompanyBySemUserId(Integer userIdKAD, int page) {
		List<CompanyInfo> list = manageCompanyInfoService.getCompanyBySemUserId(userIdKAD, page,
				WebConstants.MAX_REQUEST_ROW_EACH);
		if (list != null && !list.isEmpty()) {
			for (CompanyInfo companyInfo : list) {
				try {
					if (companyInfo.getUserId() != null) {
						User user = commonDao.getEntity(User.class, companyInfo.getUserId());
						if (user != null) {
							// 暂时显示管理职员的名字
							companyInfo.setUsername(user.getEmployeeName());
						} else {
							logger.info(
									"公司id:" + companyInfo.getId() + ",semId：" + companyInfo.getUserId() + ",找不到sem用户");
						}
					}

					if (isCompanyHasBaidu(companyInfo.getId())) {
						companyInfo.setIsHasBaiduData("1");
					} else {
						companyInfo.setIsHasBaiduData("0");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return list;
	}

	/**
	 * 更新公司信息-远程调用
	 * 
	 * @param companyInfo
	 */
	public void updateCompanyInfo(CompanyInfo companyInfo) {
		manageCompanyInfoService.updateCompany(companyInfo);
	}

	/**
	 * 根据行业查找公司(只显示有百度数据查看的公司)-远程调用
	 * 
	 * @param industryId
	 *            行业id
	 * @return 公司列表
	 */
	public List<CompanyInfo> getCompanyByIndustry_ws(String industryId) {
		List<CompanyInfo> list = new ArrayList<>();
		List<CompanyInfo> companyInfoList = manageCompanyInfoService.getCompanyByIndustry_ws(industryId);
		if (companyInfoList != null && !companyInfoList.isEmpty()) {
			for (CompanyInfo companyInfo : companyInfoList) {
				try {
					if (companyInfo.getUserId() != null) {
						User user = commonDao.getEntity(User.class, companyInfo.getUserId());
						if (user != null) {
							// 暂时显示管理职员的名字
							companyInfo.setUsername(user.getEmployeeName());
						} else {
							logger.info(
									"公司id:" + companyInfo.getId() + ",semId：" + companyInfo.getUserId() + ",找不到sem用户");
						}
					}

					// 只显示有百度数据查看的公司
					if (isCompanyHasBaidu(companyInfo.getId())) {
						companyInfo.setIsHasBaiduData("1");
						list.add(companyInfo);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return list;
	}

	public List<VisitAccessKeywordDay> getUserIdByIndustryId(String industryId, String startTime, String endTime) {
		List<VisitAccessKeywordDay> companyInfoList = manageCompanyInfoService.getYsbKeywordByIndustryId(industryId,
				startTime, endTime);
		return companyInfoList;
	}

	/**
	 * 根据行业查找公司-远程调用(需求不同对getCompanyByIndustry_ws方法修改)
	 * 
	 * @param industryId
	 *            行业id
	 * @return 公司列表
	 */
	public List<CompanyInfo> getCompanyByIndustry(String industryId) {
		List<CompanyInfo> list = new ArrayList<>();
		List<CompanyInfo> companyInfoList = manageCompanyInfoService.getCompanyByIndustry_ws(industryId);
		if (companyInfoList != null && !companyInfoList.isEmpty()) {
			for (CompanyInfo companyInfo : companyInfoList) {
				try {
					if (companyInfo.getUserId() != null) {
						User user = commonDao.getEntity(User.class, companyInfo.getUserId());
						if (user != null) {
							// 暂时显示管理职员的名字
							companyInfo.setUsername(user.getEmployeeName());
						} else {
							logger.info(
									"公司id:" + companyInfo.getId() + ",semId：" + companyInfo.getUserId() + ",找不到sem用户");
						}
					}
					list.add(companyInfo);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return list;
	}

	/**
	 * 根据行业查找关键词(百度数据)
	 * 
	 * @param industryId
	 * @return 关键词信息
	 */

	public List<BaiduPromoteInfo> getKeyInfoByIndustryBd(String industryId, String startTime, String endTime) {

		List<CompanyInfo> companyByIndustry = this.getCompanyByIndustry(industryId);
		List<BaiduPromoteInfo> result = new ArrayList<BaiduPromoteInfo>();
		int length = companyByIndustry.size();
		if (companyByIndustry.get(0).getId() == 0) {
			return result;
		} else {
			StringBuffer companyIdsSql = new StringBuffer();
			for (int i = 0; i < length; i++) {
				Integer companyId = companyByIndustry.get(i).getId();
				companyIdsSql = companyIdsSql.append("'").append(companyId).append("'").append(",");

			}
			companyIdsSql.deleteCharAt(companyIdsSql.length() - 1);
			List<Map<String, Object>> baiduKeywordInfo = this.getBaiduKeywordInfo(companyIdsSql, startTime, endTime);
			BaiduPromoteInfo bdpi;
			DecimalFormat df = new DecimalFormat("######0.00");
			for (Map<String, Object> map : baiduKeywordInfo) {
				bdpi = new BaiduPromoteInfo();
				bdpi.setKeywordSearch((String) map.get("keyword_search")); // 搜索关键词
				int numberClick = Integer.valueOf(String.valueOf(map.get("number_click")));
				bdpi.setNumberClick(numberClick); // 点击量
				int totalnumberConsult = Integer.valueOf(String.valueOf(map.get("totalnumber_consult")));
				bdpi.setConversionRate(Double.parseDouble(df.format((double)totalnumberConsult / numberClick))); // 转化率
				bdpi.setTotalnumberConsult(Integer.valueOf(String.valueOf(map.get("totalnumber_consult")))); // 咨询量
				Double consume = Double.valueOf(String.valueOf(map.get("consume")));
				bdpi.setConsume(consume);
				if (totalnumberConsult == 0) {// 转化成本。 当咨询量为0时无穷大，显示-1
					bdpi.setConversionCost(-1);
				} else {
					bdpi.setConversionCost(Double.parseDouble(df.format(consume / totalnumberConsult)));
				}
				if (companyByIndustry.size() >= 0) {
					bdpi.setIndustryName(companyByIndustry.get(0).getIndustry()); // 行业
				}
				result.add(bdpi);
			}
			return result;
		}



	}

	public List<Map<String, Object>> getBaiduKeywordInfo(StringBuffer companyIdsSql, String startTime, String endTime) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT keyword_search,SUM(number_click) AS 'number_click',")
				.append("SUM(totalnumber_consult) AS 'totalnumber_consult',")
				.append("SUM(consume) AS 'consume' FROM origin_baidu").append(" WHERE")
				.append(" origin_baidu.company_id IN ( ").append(companyIdsSql).append(")");
		if ("".equals(startTime) && "".equals(endTime)) {

			sql.append(" AND TO_DAYS(`origin_baidu`.`promotion_date`) = TO_DAYS(NOW()-1)");
		}
		if (!"".equals(endTime) && !"".equals(endTime)) {
			sql.append(" AND `origin_baidu`.`promotion_date` BETWEEN '").append(startTime).append("' AND '")
					.append(endTime).append("'");
		}
		if (!"".equals(startTime) && "".equals(endTime)) {
			sql.append(" AND `origin_baidu`.`promotion_date` BETWEEN '").append(startTime).append("' AND NOW()-1");
		}
		if ("".equals(startTime) && !"".equals(endTime)) {
			sql.append(" AND TO_DAYS(`origin_baidu`.`promotion_date`) = TO_DAYS('").append(endTime).append("')");
		}
		sql.append(" AND keyword_search not in('百度外链','直接访问','360外链')")
		.append(" GROUP BY(origin_baidu.`keyword_search`)").append(" LIMIT 10000");
		// System.out.println(sql);

		List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(String.valueOf(sql));
		return queryForList;
	}

	/**
	 * 根据行业查找关键词(易数宝数据)
	 * 
	 * @param industryId
	 * @return 易数宝关键词列表
	 */
	@Override
	public List<VisitAccessKeywordDay> getYsbKeywordByIndustryId(String industryId, String startTime, String endTime) {
		List<VisitAccessKeywordDay> ysbKeywordByIndustryId = manageCompanyInfoService
				.getYsbKeywordByIndustryId(industryId, startTime, endTime);
		return ysbKeywordByIndustryId;
	}

	/**
	 * 获取广告到期的公司信息-远程调用
	 * 
	 * @return 广告到期的公司信息
	 */
	@Override
	@Deprecated
	public List<AdOfflineCompanyInfo> getAdOfflineCompanyInfo_ws(Integer userIdKAD, int page) {
		List<AdOfflineCompanyInfo> list = new ArrayList<>();

		List<AdOfflineCompanyInfo> companyInfoList = manageCompanyInfoService.getAdOfflineCompanyInfo_ws(userIdKAD,
				page, WebConstants.MAX_REQUEST_ROW_EACH);
		if (companyInfoList != null && !companyInfoList.isEmpty()) {
			for (AdOfflineCompanyInfo companyInfo : companyInfoList) {
				try {
					if (companyInfo.getUserId() != null) {
						User user = commonDao.getEntity(User.class, companyInfo.getUserId());
						if (user != null) {
							// 暂时显示管理职员的名字
							companyInfo.setUsername(user.getEmployeeName());
						} else {
							logger.info(
									"公司id:" + companyInfo.getId() + ",semId：" + companyInfo.getUserId() + ",找不到sem用户");
						}
					}

					list.add(companyInfo);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return list;
	}

	/**
	 * 获取sem要 管理的百度推广公司-远程调用
	 * 
	 * @param userIdKAD
	 *            sem用户id
	 * @return
	 */
	@Override
	public List<CompanyInfo> getRemoteCompanyBySemUserId_baidu(Integer userIdKAD, int page) {
		List<CompanyInfo> list = manageCompanyInfoService.getCompanyBySemUserId_baidu(userIdKAD, page,
				WebConstants.MAX_REQUEST_ROW_EACH);
		if (list != null && !list.isEmpty()) {
			for (CompanyInfo companyInfo : list) {
				try {
					if (companyInfo.getUserId() != null) {
						User user = commonDao.getEntity(User.class, companyInfo.getUserId());
						if (user != null) {
							// 暂时显示管理职员的名字
							companyInfo.setUsername(user.getEmployeeName());
						} else {
							logger.info(
									"公司id:" + companyInfo.getId() + ",semId：" + companyInfo.getUserId() + ",找不到sem用户");
						}
					}

					if (isCompanyHasBaidu(companyInfo.getId())) {
						companyInfo.setIsHasBaiduData("1");
					} else {
						companyInfo.setIsHasBaiduData("0");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		return list;
	}



	public void deleteCompanyBackup(Integer id) {
		String hql = "from Backup where id=?";
		List<Backup> backups = commonDao.findHql(hql, id);
		if(!backups.isEmpty()){
			String path = backups.get(0).getPath();
			File file = new File(path);
			file = new File(file.getAbsolutePath());
			boolean result = file.delete();
			if(result){
				commonDao.executeHql("delete Backup where id="+id );
			}
		}
		
		
		
			
		}
//			commonDao.
//			
//			int num = commonDao.executeHql("from Backup where companyId="+companyId);
//			commonDao.findUniqueByProperty(Backup.class, "companyId", companyId);
//			if(num>0) {
//				
//				System.out.println("123");
//			} else{
//				return;
//			}
		
		

	

	@Override
	public void signCompanyBackup(Integer id) {
		
		commonDao.executeHql("update Backup set isGood = 1 where id="+id);
	
	}

	public void downloadBackup(Integer id){
		commonDao.getCompanyPath(id);
	}

	public void cancelCompanyBackup(Integer id){
		commonDao.executeHql("update Backup set isGood = 0 where companyId="+id);
	}

	@Override
	public void deleteCompanyAllBackup(Integer companyId) {
		String hql = "delete from Backup where companyId="+companyId;
		commonDao.executeHql(hql);
	}

}
